package com.winchain.chainbill.receivables.biz.impt.cmd;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.sequence.SequenceHelper;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.receivables.base.po.ArOperation;
import com.winchain.chainbill.receivables.base.po.ArRecord;
import com.winchain.chainbill.receivables.base.service.ArOptService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ReceivablesArNoCmd
  implements ICommand<ArRecord>
{
  protected final Log logger = LogFactory.getLog(getClass());
  @Autowired
  private ArOptService arOptService;
  @Autowired
  private CusRecService basCusService;
  
  public boolean execute(CommandContext<ArRecord> context)
    throws Exception
  {
    ArRecord record = (ArRecord)context.getSource();
    int optSeq = record.getOptSeq().intValue();
    
    ArOperation opt = (ArOperation)context.getValue("Operation");
    boolean timeout = false;
    ArOperation lastOpt = this.arOptService.getByBizIdAndSeqNo(record.getArId(), optSeq);
    String lastLimitDate = lastOpt.getLimitDate();
    if (StringUtil.notEmpty(lastLimitDate)) {
      timeout = ChainBillUtil.isTimeout(lastLimitDate);
    }
    context.setValue("Timeout", Boolean.valueOf(timeout));
    if (!timeout)
    {
      opt.setNoTimeout(Boolean.valueOf(true));
      
      String arNo = getArNo(context);
      record.setArNo(arNo);
    }
    return false;
  }
  
  private String getArNo(CommandContext<ArRecord> context)
  {
    ArRecord record = (ArRecord)context.getSource();
    String buyerId = record.getBuyerId();
    String cusCode = ((CusRec)this.basCusService.selectByKey(buyerId)).getCusCode();
    String finId = "";
    
    CusRec fin = (CusRec)this.basCusService.selectByKey(finId);
    
    context.setValue("Fin", fin);
    
    StringBuilder builder = new StringBuilder();
    builder.append(getFormativeCusCode(fin.getCusCode()));
    builder.append(getFormativeCusCode(cusCode));
    
    String sysDate = DateUtil.get4BitYearAndMounth();
    
    builder.append(sysDate);
    builder.append(getSerialNo(cusCode));
    return builder.toString();
  }
  
  private String getFormativeCusCode(String cusCode)
  {
    return cusCode;
  }
  
  private String getSerialNo(String cusCode)
  {
    return SequenceHelper.generateCode(cusCode, 4);
  }
}
